import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wu_you/data/repository/mall_repository.dart';
import 'package:wu_you/data/repository/user_repository.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/model/mall/mall_model.dart';
import 'package:wu_you/model/user/user_model.dart';
import 'package:wu_you/page/user/page_address_manager.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/route/app_routers.dart';
import 'package:wu_you/state/bloc/http_bloc.dart';
import 'package:wu_you/state/bloc/user_bloc.dart';
import 'package:wu_you/utils/navigator_util.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/widgets/appbar_leading.dart';
import 'package:wu_you/widgets/dialog_general.dart';
import 'package:wu_you/widgets/http_status_widget.dart';
import 'package:wu_you/widgets/pay_dialog.dart';
import 'package:toast/toast.dart';

class ExcProductPreViewPage extends StatefulWidget{
  final NewProductSkuModel productSkuModel;
  final GoodsDetail model;
  final int number;
  ExcProductPreViewPage({Key key,this.productSkuModel,this.model,this.number}):super(key: key);
  @override
  ExcProductPreViewPageState createState() => ExcProductPreViewPageState();
}
class ExcProductPreViewPageState extends State<ExcProductPreViewPage>{
  bool flag = false;
  AddressModel _receiveAddressModel;
  String addressId;
  FocusNode _commentFocus = FocusNode();
  String _expressRemark;

  var message;

  String payType = "2";
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    double width = MediaQuery.of(context).size.width;
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        leading: AppBarLeading.leading("ic_mall_back"),
        title: Text('${message['product7']}'),
        flexibleSpace: Container(
          height: 300,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [AppColors.primaryColor, AppColors.primaryColor],
            ),
          ),
        ),
      ),
      body: Stack(
        children: [
          AspectRatio(
            aspectRatio: 4,
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  colors: [AppColors.primaryColor, AppColors.primaryColor],
                ),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.symmetric(horizontal: 16),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(8),
                topRight: Radius.circular(8),
              ),
              color: Colors.white,
            ),
            child: HttpWidget<AddressModel, DefaultAddressBloc>(
                create: (context) => DefaultAddressBloc()..add(HttpEvent()),
                child: (context, data) {
                  if (flag == false) {
                    _receiveAddressModel = data;
                    addressId = _receiveAddressModel.id;
                  }
                  Widget child;
                  if (_receiveAddressModel.mobile != null ||
                      _receiveAddressModel.name != null) {
                    child = ListTile(
                      contentPadding:
                      EdgeInsets.only(left: 0, right: 0, top: 12, bottom: 12),
                      leading: CircleAvatar(
                        child: Icon(
                          Icons.location_on_outlined,
                          color: Colors.white,
                        ),
                        backgroundColor: AppColors.primaryColor,
                      ),
                      title: Text.rich(
                        TextSpan(
                          children: [
                            TextSpan(
                              text: '${_receiveAddressModel.name}',
                              style:
                              TextStyle(fontSize: 14, color: AppColors.textColor),
                            ),
                            TextSpan(
                              text: '   ${_receiveAddressModel.mobile}',
                              style: TextStyle(
                                  fontSize: 12, color: AppColors.textHintColor),
                            ),
                          ],
                        ),
                      ),
                      subtitle: Text(
                        '${_receiveAddressModel.detailed_address}',
                        style: TextStyle(fontSize: 12, color: AppColors.textColor),
                      ),
                      trailing: Icon(Icons.chevron_right_rounded),
                    );
                  } else {
                    child = Padding(
                        padding: EdgeInsets.only(top: 25, bottom: 25),
                        child: Row(
                          children: [
                            CircleAvatar(
                              child: Icon(
                                Icons.location_on_outlined,
                                color: Colors.white,
                              ),
                              backgroundColor: AppColors.primaryColor,
                            ),
                            SizedBox(width: 12,),
                            Text('${message['product8']}'),
                          ],
                        )
                    );
                  }
                  // Widget ch;
                  // if (addressId != null) {
                  //   ch = Text("包邮", style: TextStyle(fontSize: 16, color: AppColors.primaryColor));
                  // } else {
                  //   ch = Text("包邮");
                  // }
                  return Padding(
                    padding: EdgeInsets.only(left: 12, right: 12),
                    child: ListView(
                      children: [
                        GestureDetector(
                          onTap: () {
                            // TODO: 当前页底部弹起地址选择
                            showModalBottomSheet(
                                context: context,
                                isScrollControlled: true,
                                backgroundColor: Colors.transparent,
                                builder: (ctx) {
                                  return DialogGeneral(
                                    title: "${message['address1']}",
                                    minHeight: width * 1.2,
                                    padding: EdgeInsets.zero,
                                    child: AddressDataView(
                                      callback: (model) {
                                        setState(() {
                                          flag = true;
                                          _receiveAddressModel = model;
                                          addressId = _receiveAddressModel.id;
                                        });
                                      },
                                    ),
                                  );
                                });
                          },
                          child: child,
                        ),
                        Row(
                          children: [
                            Image.asset(Utils.getImgPath('ic_mall_unselect'),width: 18,height: 18,)
                            // Padding(
                            //   padding: EdgeInsets.only(left: 8),
                            //   child: Text(detail.info.merShortName),
                            // ),
                          ],
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(vertical: 8),
                          child: Divider(),
                        ),
                        IntrinsicHeight(
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              ClipRRect(
                                borderRadius: BorderRadius.circular(4),
                                child: Image.network(
                                  widget.productSkuModel.sku_img_url != ""
                                      ? widget.productSkuModel.sku_img_url
                                      : widget.model.img_url,
                                  fit: BoxFit.fill,
                                  height: 96,
                                  width: 96,
                                  errorBuilder: (context,err,stackTrace){
                                    return Image.asset(Utils.getImgPath('ic_logo'),width: 96,height: 96,);
                                  },
                                ),
                              ),
                              VerticalDivider(
                                width: 8,
                                color: Colors.transparent,
                              ),
                              Expanded(
                                child: Column(
                                  mainAxisSize: MainAxisSize.max,
                                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      "${widget.model.name}",
                                      style: TextStyle(
                                          fontSize: 14, color: AppColors.textColor),
                                    ),
                                    Text(
                                      widget.productSkuModel != null
                                          ? "${message['product33']}: ${widget.productSkuModel.spec_name}"
                                          : "",
                                      style: TextStyle(
                                          fontSize: 14, color: AppColors.textHintColor),
                                    ),
                                    Row(
                                      children: [
                                        Text(
                                          _buyPrice(),
                                          style: TextStyle(
                                              fontSize: 16,
                                              color: AppColors.primaryColor),
                                        ),
                                        Spacer(),
                                        Text(
                                          "x${widget.number}",
                                          style: TextStyle(
                                              fontSize: 16,
                                              color: AppColors.textHintColor),
                                        ),
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        Divider(),
                        ListTile(
                          contentPadding: EdgeInsets.zero,
                          leading: Text('${message['product9']}'),
                          trailing: Text(
                           '${message['product36']}', style: TextStyle(fontSize: 16, color: AppColors.primaryColor)
                          )
                        ),
                        Divider(),
                        // ListTile(
                        //   contentPadding: EdgeInsets.zero,
                        //   leading: Text('运费'),
                        //   trailing: ch,
                        // ),
                        // Divider(),
                        TextField(
                          focusNode: _commentFocus,
                          style: Theme.of(context).textTheme.bodyText2,
                          maxLines: 1,
                          textAlignVertical: TextAlignVertical.center,
                          textInputAction: TextInputAction.done,
                          keyboardType: TextInputType.text,
                          maxLength: 64,
                          onChanged: (value) {
                            this._expressRemark = value;
                          },
                          controller: TextEditingController(text: _expressRemark),
                          decoration: InputDecoration(
                            fillColor: Colors.white,
                            prefixIcon: Align(
                              alignment: Alignment.centerLeft,
                              child: Text("${message['product10']}",
                                  style: Theme.of(context).textTheme.bodyText2),
                            ),
                            prefixIconConstraints: BoxConstraints.loose(Size(48, 48)),
                            filled: true,
                            border: OutlineInputBorder(
                              borderSide: BorderSide.none,
                            ),
                            counterText: '',
                            hintText: "${message['product10']}",
                            hintStyle: Theme.of(context).textTheme.bodyText1,
                          ),
                        ),
                        Divider(),
                        // Padding(
                        //   padding: EdgeInsets.only(top: 12),
                        //   child: Text("支付方式",
                        //       style: Theme.of(context).textTheme.bodyText2),
                        // ),
                        // Column(
                        //   children: [
                            // ListTile(
                            //   leading: Text("消费积分",style: TextStyle(color: AppColors.primaryColor),),
                            //   contentPadding: EdgeInsets.zero,
                            //   trailing: Image.asset(Utils.getImgPath(payType == "1" ? 'ic_pay_tick':'ic_pay_circle'),width: 22,height: 22,),
                            //   onTap: (){
                            //     setState(() {
                            //       payType = "1";
                            //     });
                            //   },
                            // ),
                            // Divider(),
                      //       ListTile(
                      //         leading: Text("无忧积分",style: TextStyle(color: AppColors.primaryColor),),
                      //         contentPadding: EdgeInsets.zero,
                      //         trailing: Image.asset(Utils.getImgPath(payType == "2" ? 'ic_pay_tick':'ic_pay_circle'),width: 22,height: 22,),
                      //         onTap: (){
                      //           setState(() {
                      //             payType = "2";
                      //           });
                      //         },
                      //       ),
                      //       Divider(),
                      //     ],
                      //   )
                      ],
                    ),
                  );
                })
          )
        ],
      ),
      bottomNavigationBar: SafeArea(
        top: false,
        bottom: true,
        left: false,
        right: false,
        child: Row(
          children: [
            Expanded(
                flex: 4,
                child: Container(
                  height: 56,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black54,
                        offset: Offset(2.0, 2.0),
                        blurRadius: 4.0),
                    ],
                  ),
                  child: RichText(
                    text: TextSpan(children: [
                      TextSpan(
                          text: "${message['product12']}:",
                          style: TextStyle(color: AppColors.textColor)),
                      TextSpan(
                          text: _allPrice(),
                          style: TextStyle(
                              fontSize: 16, color: AppColors.primaryColor)),
                    ]),
                    textAlign: TextAlign.center,
                  ),
                )
            ),
            Expanded(
              flex: 2,
              child: GestureDetector(
                onTap: () {
                  intervalClick(1);
                },
                child: Container(
                  height: 56,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [Color(0xffff6600), Color(0xffff9933)],
                    ),
                  ),
                  child: Text(
                    "${message['product13']}",
                    style: TextStyle(fontSize: 16, color: Colors.white),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _buyPrice(){
    if(payType == "1"){
      return "消费积分:${(double.parse("${widget.productSkuModel.sku_sell_price}") * widget.number).toStringAsFixed(4)}";
    }else if(payType == "2"){
      return "无忧积分:${(double.parse("${widget.productSkuModel.sku_linglong_price}") * widget.number).toStringAsFixed(4)}";
    }else{
      return "";
    }
  }


  String _allPrice(){
    if(payType == "1"){
      return "${(double.parse("${widget.productSkuModel.sku_sell_price}") * widget.number).toStringAsFixed(4)}";
    }else if(payType == "2"){
      return "${(double.parse("${widget.productSkuModel.sku_linglong_price}") * widget.number).toStringAsFixed(4)}";
    }else{
      return "";
    }

  }
  ///手续费显示
  String _commission(){
    if(double.parse("${widget.model.fees}") > 0){
      String commission = "${(double.parse("${widget.productSkuModel.fees}") * widget.number).toStringAsFixed(4)}";
      return commission;
    }else{
      return '无';
    }
  }

  var lastPopTime = DateTime.now();
  void intervalClick(int needTime) {
    if (lastPopTime == null || DateTime.now().difference(lastPopTime) > Duration(seconds: needTime)) {
      lastPopTime = DateTime.now();
      _pay();
    } else {
      // print("重复！");
    }
  }
  void _pay() async{
    if (addressId == null) {
      ToastUtils.show("${message['product8']}", context);
      return;
    }
    String pwd = await _inputTradePassword();
    if (pwd == null) {
      ToastUtils.show("${message['product14']}", context);
      return;
    }
    LoadingApi.func(MallRepository.goodsBuyExchange(addressId, widget.productSkuModel.sku_id,
        widget.number, pwd,_expressRemark), context,complete: (v){
      ToastUtils.show("${message['Success']}", context);
      NavigatorUtil.navigateToNamed(context, AppRoutes.mallOrder);
    },error: (e){
      ToastUtils.show("$e", context);
    });
    // if(payType == "1"){
    //   String pwd = await _inputTradePassword();
    //   if (pwd == null) {
    //     ToastUtils.show("${message['product14']}", context);
    //     return;
    //   }
    //   LoadingApi.func(MallRepository.goodsbuy(addressId, widget.productSkuModel.sku_id,
    //       widget.number, pwd,_expressRemark), context,complete: (v){
    //     ToastUtils.show("${message['Success']}", context);
    //     NavigatorUtil.navigateToNamed(context, AppRoutes.mallOrder);
    //   },error: (e){
    //     ToastUtils.show("$e", context);
    //   });
    // }else if(payType == "2"){
    //   String pwd = await _inputTradePassword();
    //   if (pwd == null) {
    //     ToastUtils.show("${message['product14']}", context);
    //     return;
    //   }
    //   LoadingApi.func(MallRepository.goodsBuyLinglong(addressId, widget.productSkuModel.sku_id,
    //       widget.number, pwd,_expressRemark), context,complete: (v){
    //     ToastUtils.show("${message['Success']}", context);
    //     NavigatorUtil.navigateToNamed(context, AppRoutes.mallOrder);
    //   },error: (e){
    //     ToastUtils.show("$e", context);
    //   });
    // }
  }
  Future<String> _inputTradePassword() async {
    String pwd = await showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return PayDialog();
      },
    );
    if (pwd == null) {
      return null;
    }
    return pwd;
  }
}



///地址栏
typedef CallBack = void Function(AddressModel model);
class AddressDataView extends StatefulWidget {
  final CallBack callback;

  AddressDataView({
    Key key,
    this.callback,
  }) : super(key: key);

  @override
  AddressDataViewState createState() => AddressDataViewState();
}

class AddressDataViewState extends State<AddressDataView> {
  String _selectedId = "0";
  BuildContext ctx;

  var message;
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return BlocProvider.value(
        value: ReceiveAddressBloc(),
        child: Scaffold(
            backgroundColor: Colors.white,
            body: HttpWidget<List<AddressModel>, ReceiveAddressBloc>(
              create: (context) => BlocProvider.of<ReceiveAddressBloc>(context)
                ..add(HttpEvent()),
              child: (context, data) {
                if (_selectedId == "0") {
                  data.forEach((element) {
                    if (element.isdefault == "1") {
                      _selectedId = element.id;
                    }
                  });
                }
                ctx = context;
                return ListView.separated(
                    itemCount: data.length,
                    separatorBuilder: (context, index) {
                      return Divider(height: 4, color: Colors.transparent);
                    },
                    itemBuilder: (context, index) {
                      AddressModel item = data[index];
                      return ListTile(
                        onTap: () {
                          if (item != null) {
                            widget.callback(item);
                            _changeSelected(item.id);
                            Navigator.pop(context, item);
                          }
                        },
                        leading: Radio(
                          value: item.id,
                          groupValue: _selectedId,
                          onChanged: _changeSelected,
                        ),
                        title: Text.rich(
                          TextSpan(
                            children: [
                              TextSpan(
                                text: '${item.name}',
                                style: TextStyle(
                                    fontSize: 14, color: AppColors.textColor),
                              ),
                              TextSpan(
                                text: '   ${item.mobile}',
                                style: TextStyle(
                                    fontSize: 12,
                                    color: AppColors.textHintColor),
                              ),
                            ],
                          ),
                        ),
                        subtitle: item.detailed_address != null
                            ? Text(
                          "${item.detailed_address}",
                          style: TextStyle(fontSize: 12, color: AppColors.textColor),
                          maxLines: 3,
                        )
                            : Text(""),
                        // trailing: IconButton(
                        //   icon: Icon(
                        //     Icons.edit,
                        //     color: Colors.grey,
                        //   ),
                        //   onPressed: () {
                            // NavigatorUtil.navigateToPage(
                            //     context,
                            //     EditReceiveAddressPage(
                            //       model: item,
                            //     )).then((value) {
                            //   if (value != null) {
                            //     BlocProvider.of<ReceiveAddressBloc>(context)
                            //         .add(HttpEvent());
                            //   }
                            // });
                        //   },
                        // ),
                      );
                    });
              },
              emptyBuilder: (context) {
                ctx = context;
                return Center(
                  child: Text("${message['trad57']}"),
                );
              },
            ),
            bottomNavigationBar: BlocBuilder<ReceiveAddressBloc, HttpState>(
                builder: (context, state) {
                  return SafeArea(
                    top: false,
                    bottom: true,
                    left: false,
                    right: false,
                    child: Container(
                      decoration: BoxDecoration(
                        gradient: LinearGradient(colors: [
                          AppColors.primaryColor,
                          AppColors.secondColor
                        ]),
                      ),
                      width: double.infinity,
                      height: 50,
                      child: TextButton(
                        child: Text("${message['address5']}"),
                        style: ButtonStyle(
                          foregroundColor: MaterialStateProperty.all(Colors.white),
                          // shape: MaterialStateProperty.all(BeveledRectangleBorder()),
                          shape:
                          MaterialStateProperty.all(BeveledRectangleBorder()),
                        ),
                        onPressed: () {
                          if (ctx == null) {
                            ctx = context;
                          }
                          NavigatorUtil.navigateToPage(
                              ctx, AddressAddPage())
                              .then((value) {
                            if (value != null) {
                              BlocProvider.of<ReceiveAddressBloc>(ctx).add(HttpEvent());
                            }
                          });
                        },
                      ),
                    ),
                  );
                })));
  }

  ///设置默认地址
  void _changeSelected(value) {
    if (_selectedId == value) {
      return;
    }
    setState(() {
      _selectedId = value;
    });
    UserRepository().updateReceiveAddress(id:value).then((value) {
      // BlocProvider.of<ReceiveAddressBloc>(ctx).add(HttpEvent());
    }).catchError((error) {
      Toast.show("$error", context);
    });
    // UserRepository()
    //     .setDefaultReceiveAddress(value)
    //     .then((value) {})
    //     .catchError((error) {
    //   ErrorHandler.handleError(error, action: (msg) {
    //     Toast.show(msg, context);
    //   });
    // });
  }
}
